package com.xjtu.platform.security.emailConfirm;

import com.xjtu.platform.common.CommonService;
import com.xjtu.platform.common.CurrentUser;
import com.xjtu.platform.common.Result;
import com.xjtu.platform.common.TokenUtils;
import com.xjtu.platform.security.register.SendMail;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Random;

@RestController
@RequestMapping("/security/EmailConfirm")
public class EmailConfirmAPI {

    static Random r=new Random();
    static int sendcode;
    @Resource
    private CommonService commonService;

    @Resource
    private EmailConfirmService emailConfirmService;


    @PostMapping("")
    public Result changePwd(@RequestBody EmailConfirmDto emailConfirmDto, @RequestHeader("Token") String token){
        String user_id = getCurrentUserIdByToken(token);
        boolean ok = emailConfirmService.confirmCode(emailConfirmDto);
        if(ok){
            return Result.success("验证成功");
        }else {
            return Result.fail(Result.ERR_CODE_BUSINESS,"验证码错误......");
        }

    }

    @PostMapping("/SendMail")
    public Result sendMail(@RequestBody EmailConfirmDto emailConfirmDto, @RequestHeader("Token") String token){
        String mail = emailConfirmDto.getEmail();
        String user_id = getCurrentUserIdByToken(token);
        String user_mail = emailConfirmService.getEmail(user_id);
        try {
            int code = sendemailcode(mail);
            boolean ok = emailConfirmService.insertFlag(code,user_id);
            commonService.setCache(user_id,"");
            if(ok){
                return Result.success("验证码发送成功!!!");
            }else {
                return Result.fail(Result.ERR_CODE_SYS,"请检查网络......");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail(Result.ERR_CODE_BUSINESS,"系统维护中.......");
        }
    }

    @PostMapping("/isEmailUnique")
    public Result isEmailUnique(@RequestBody EmailConfirmDto emailConfirmDto, @RequestHeader("Token") String token){
        String user_id = getCurrentUserIdByToken(token);
        boolean unique = emailConfirmService.isUnique(emailConfirmDto,user_id);
        if(unique){
            return Result.success("true");
        }else {
            return Result.success("false");
        }
    }




    public static int sendemailcode(String targetmail){
        try {
            int code=r.nextInt(900000)+100000;
            SendMail.send(targetmail,"您的验证码为： \n"+ code+"\n"+"有效时间为10分钟");
            sendcode=code;
            return sendcode;

        } catch (Exception e) {
            e.printStackTrace();
            return 0;

        }

    }

    public String getCurrentUserIdByToken(String token)
    {
        CurrentUser currentUser = TokenUtils.getUserInfo(token,commonService);
        System.out.println(currentUser);
        return currentUser.getUserId();
    }
}
